package springframework.beans.factory.support;

import springframework.beans.BeansException;
import springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author lzp
 * @Date:2023/3/13
 * @description: JDK实例化对象策略
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

	/**
	 * jdk实例化对象的视线
	 *
	 * @param beanDefinition bean对象
	 * @param beanName       bean缓存的名称
	 * @param ctor           bean的构造器
	 * @param args           构造函数所需的入参
	 * @return
	 */
	@Override
	public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) {
		Class clazz = beanDefinition.getBeanClass();

		try {
			if (null != ctor) {
				return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
			} else {
				// 调用无参构造
				return clazz.getDeclaredConstructor().newInstance();
			}
		} catch (InvocationTargetException | InstantiationException | IllegalAccessException |
				 NoSuchMethodException e) {
			throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
		}

	}

}
